<?php
/**
 * Created by 1971599474@qq.com
 * User: zhixuan
 * Date: 2020/1/25
 * Time: 23:19
 */

namespace app\index\controller;
use app\common\model\AreaRegion;
use app\common\model\Cart as CartModel;
use app\common\model\Coupon;
use app\common\model\MemberAddress;
use app\common\model\Order;
use app\common\model\Region;
use app\common\model\Goods as GoodsModel;
use app\common\model\Member;
use app\common\model\Shipping;
use app\common\model\ShippingArea;
use app\common\model\SpecGoodsPrice;
use app\common\model\Discount as DiscountModel;
use app\common\utils\JsonService;
use think\facade\Db;
use think\response\Json;

class Cart extends Base
{

    public function initialize()
    {
        parent::initialize(); //
        if(!session('member_id')){
            if(!request()->isAjax()) {
                $this->redirect(url('index/login/login',['returnUrl'=>input('returnUrl','')])->suffix(false)->build());
            }else{
                return JsonService::error('请登录',-1);
            }
        }
        $member = Member::getOne(['id'=>$this->member_id]);
        $this->assign('member',$member);
    }

    public function index(){
       $cartTemp= CartModel::where(['user_id'=>$this->member_id])->with(['getShop','getGoods'])->select();
       $cartList = [];
       foreach($cartTemp as $k=>$v){
           $goodsList[$v['shop_id']][] = [
               'cart_id'=>$v['id'],
               'goods_id'=>$v['goods_id'],
               'user_id'=>$v['user_id'],
               'shop_id'=>$v['shop_id'],
               'original_img'=>$v['getGoods']['original_img'],
               'goods_name'=>$v['goods_name'],
               'market_price'=>$v['market_price'],
               'goods_price'=>$v['goods_price'],
               'goods_num'=>$v['goods_num'],
               'spec_price_goods_id'=>$v['spec_price_goods_id'],
               'spec_key'=>$v['spec_key'],
               'spec_key_name'=>$v['spec_key_name'],
               'add_time'=>$v['add_time'],
           ];

           $cartList[$v['shop_id']] = [
               'shop_id'=>$v['shop_id'],
               'shop_name'=>$v['getShop']['shop_name'],
               'goodsList'=>$goodsList[$v['shop_id']],
           ];
       }

       $this->assign('cartList',$cartList);
       return $this->fetch();
    }

    public function cart2(){
        $post = $this->request->post();
        $goods_id = isset($post['goods_id'])?$post['goods_id']:0;
        $goods_num = isset($post['goods_num'])?$post['goods_num']:0;
        $spec_item_id = isset($post['spec_item_id'])?$post['spec_item_id']:0;
        $cart_ids = isset($post['cart_id'])?$post['cart_id']:[];
        $shop_id = 0;

        //商品列表
        $goodsList = [];
        $total_price = 0;
        $total_integral = 0;
        if(!empty($cart_ids) && is_array($cart_ids)){
            $where[] = ['user_id','=',$this->member_id];
            $where[] = ['id','in',$cart_ids];
            $cartList = CartModel::where($where)->with(['getShop','getGoods'])->select();
            foreach($cartList as $k=>$v){
                $real_price = $v['getGoods']['shop_price'] * $v['goods_num'];
                $price_desc = '';
                $price = $v['getGoods']['shop_price'] * $v['goods_num'];

                $integral = $v['getGoods']['exchange_integral'];
                //是否折扣商品
                $time = time();
                $where2 = [['goods_id','=',$v['goods_id']],['start_time','<',$time],['end_time','>',$time]];
                $discount = DiscountModel::getOne($where2);

                if(!empty($discount) && $integral > 0){
                    $price_desc = ($price*$discount['rate']/100).'+'.$integral.'积分';
                    $price = $price*$discount['rate']/100;
                }else if(!empty($discount)){
                    $price_desc = $price*$discount['rate']/100;
                    $price = $price*$discount['rate']/100;
                }else if($integral > 0){
                    $price_desc = $price.'+'.$integral.'积分';
                }

                $spec = SpecGoodsPrice::getOne(['item_id'=>$v['spec_price_goods_id'],'goods_id'=>$v['goods_id'],'key'=>$v['spec_key']],'item_id,key,key_name,price');
                $v['key_name'] = '';

                if(!empty($spec)){
                    $v['key_name'] = $spec['key_name'];
                    $price = $spec['price']*$v['goods_num'];
                    $real_price = $spec['price']*$v['goods_num'];
                    if(!empty($discount) && $integral > 0){
                        $price_desc = ($price*$discount['rate']/100).'+'.$integral.'积分';
                        $price = $price*$discount['rate']/100;
                    }else if(!empty($discount)){
                        $price_desc = $price*$discount['rate']/100;
                        $price = $price*$discount['rate']/100;
                    }else if($integral > 0){
                        $price_desc = $price.'+'.$integral.'积分';
                    }
                }
                $goodsList[] = [
                    'goods_id'=>$v['goods_id'],
                    'shop_id'=>$v['shop_id'],
                    'spec_price_goods_id'=>$v['spec_price_goods_id'],
                    'goods_name'=>$v['getGoods']['goods_name'],
                    'key_name'=>$v['key_name'],
                    'shop_price'=>$real_price,
                    'real_price'=>$price,
                    'price_desc'=>$price_desc,
                    'original_img'=>$v['getGoods']['original_img'],
                    'cart_id'=>$v['id'],
                    'integral'=>$integral,
                    'goods_num'=>$v['goods_num']
                ];
                $shop_id = $v['shop_id'];
                $total_integral += $integral;
                $total_price += $price;
            }
        }else {
            if (!$goods_id) {
                exit('<script>alert("非法参数");history.go(-1);</script>');
            }
            if ($goods_id && $goods_num < 1) {
                exit('<script>alert("购买数量必须至少为一个");history.go(-1);</script>');
            }

            $goods = GoodsModel::getOne(['goods_id' => $goods_id], 'goods_id,shop_id,goods_name,shop_price,original_img,goods_type,sales_sum,comment_count,store_count,exchange_integral,is_free_shipping,weight')->toArray();
            $price = $goods['shop_price'] * $goods_num;
            $real_price = $goods['shop_price'] * $goods_num;
            $price_desc = '';
            $integral = $goods['exchange_integral'];
            $goods['key_name'] = '';

            //是否折扣商品
            $time = time();
            $where2 = [['goods_id','=',$goods_id],['start_time','<',$time],['end_time','>',$time]];
            $discount = DiscountModel::getOne($where2);
            if(!empty($discount) && $integral > 0){
                $price_desc = ($price*$discount['rate']/100).'+'.$integral.'积分';
                $price = $price*$discount['rate']/100;
            }else if(!empty($discount)){
                $price_desc = $price*$discount['rate']/100;
                $price = $price*$discount['rate']/100;
            }else if($integral > 0){
                $price_desc = $price.'+'.$integral.'积分';
            }

            if($spec_item_id > 0){
                $spec = SpecGoodsPrice::getOne(['item_id'=>$spec_item_id,'goods_id'=>$goods['goods_id']],'item_id,key,key_name,price');
                if(!empty($spec)){
                    $goods['key_name'] = $spec['key_name'];
                    $price = $spec['price'] * $goods_num;
                    $real_price = $spec['price'] * $goods_num;

                    if(!empty($discount) && $integral > 0){
                        $price_desc = ($price*$discount['rate']/100).'+'.$integral.'积分';
                        $price = $price*$discount['rate']/100;
                    }else if(!empty($discount)){
                        $price_desc = $price*$discount['rate']/100;
                        $price = $price*$discount['rate']/100;
                    }else if($integral > 0){
                        $price_desc = $price.'+'.$integral.'积分';
                    }
                }
            }

            $goods['cart_id'] = 0;
            $goods['shop_price'] = $real_price;
            $goods['real_price'] = $price;
            $goods['price_desc'] = $price_desc;
            $goods['integral'] = $integral;
            $goods['goods_num'] = $goods_num;
            $goods['spec_price_goods_id'] = $spec_item_id;
            $goodsList = [$goods];
            $total_price = $price;
            $total_integral = $integral;
            $shop_id = $goods['shop_id'];
        }

        $total['total_price'] = $total_price;
        $total['total_integral'] = $total_integral;
        //物流公司
        $shippingList = [];
        if($shop_id){
            $shippingList = Shipping::getAll(['shop_id'=>$shop_id]);
        }

        // 找出这个用户的优惠券 没过期的  并且 订单金额达到 condition 优惠券指定标准的
        $couponWhere = [
            ['c2.member_id','=',$this->member_id],
            ['c1.use_end_time','>', time()],
            ['c1.use_start_time','<', time()],
            ['c1.condition','<=',$total_price]
        ];

        $couponList = Db::name('coupon')->alias('c1')
            ->field('c1.name,c1.money,c1.condition,c2.*')
            ->join('coupon_list c2', ' c2.coupon_id = c1.id and c1.type in(0,1,2,3) and order_id = 0', 'left')
            ->where($couponWhere)
            ->select();

        $this->assign('couponList',$couponList);
        $this->assign('goodsList',$goodsList);
        $this->assign('shippingList',$shippingList);
        $this->assign('total',$total);
        return $this->fetch('cart2');
    }


    /*
     * ajax 获取用户收货地址 用于购物车确认订单页面
    */
    public function ajaxAddress(){
        $address_list = MemberAddress::where(['member_id'=>$this->member_id,'is_pickup'=>0])->select();
        if($address_list){
            $area_id = array();
            foreach ($address_list as $val){
                $area_id[] = $val['province'];
                $area_id[] = $val['city'];
                $area_id[] = $val['district'];
                $area_id[] = $val['twon'];
            }
            $area_id = array_filter($area_id);
            $area_id = implode(',', $area_id);
            $regionList = Region::where("id", "in", $area_id)->column('name','id');
            $this->assign('regionList', $regionList);
        }
        $address_where['is_default'] = 1;
        $c = MemberAddress::where(['member_id'=>$this->member_id,'is_default'=>1,'is_pickup'=>0])->count(); // 看看有没默认收货地址
        if((count($address_list) > 0) && ($c == 0)) // 如果没有设置默认收货地址, 则第一条设置为默认收货地址
            $address_list[0]['is_default'] = 1;
        $this->assign('address_list', $address_list);
        return $this->fetch('ajax_address');
    }


    /*
     * ajax获取订单商品价格
     * */
    public function cart3(){
        $post = $this->request->post();

        $goods_id = isset($post['goods_id'])?$post['goods_id']:0;
        $goods_num = isset($post['goods_num'])?$post['goods_num']:0;
        $spec_item_id = isset($post['spec_item_id'])?$post['spec_item_id']:0;
        $cart_ids = isset($post['cart_id'])?$post['cart_id']:[];
        $shop_id = 0;

        $address_id = input("address_id/d"); //  收货地址id
        $shipping_code =  input("shipping_code"); //  物流编号
        $invoice_title = input('invoice_title'); // 发票
        $coupon_id =  input("coupon_id/d"); //  优惠券id
        $couponCode =  input("couponCode"); //  优惠券代码
        $pay_points =  input("pay_points/d",0); //  使用积分
        $user_money =  input("user_money/f",0); //  使用余额
        $user_note =  input("user_note",''); // 用户留言
        $paypwd =  input("paypwd",''); // 支付密码
        $user_money = $user_money ? $user_money : 0;

        if(!$goods_id && $cart_ids==0){
            return JsonService::error('没有结算商品');
        }

        if(!$address_id) return JsonService::error('请先填写收货人信息'); // 返回结果状态
        if(!$shipping_code) return JsonService::error('请先选择物流信息');//

        //商品列表
        $goodsList = [];
        $total_price = 0;
        $total_integral = 0;
        $weight = 0;
        if(!empty($cart_ids) && is_array($cart_ids)){
            $where[] = ['user_id','=',$this->member_id];
            $where[] = ['id','in',$cart_ids];
            $cartList = CartModel::where($where)->with(['getShop','getGoods'])->select();
            foreach($cartList as $k=>$v){
                $real_price = $v['getGoods']['shop_price'] * $v['goods_num'];
                $price_desc = '';
                $price = $v['getGoods']['shop_price'] * $v['goods_num'];
                $integral = $v['getGoods']['exchange_integral'];
                //是否折扣商品
                $time = time();
                $discount_id = 0;
                $where2 = [['goods_id','=',$v['goods_id']],['start_time','<',$time],['end_time','>',$time]];
                $discount = DiscountModel::getOne($where2);
                if(!empty($discount) && $integral > 0){
                    $discount_id = $discount['discount_id'];
                    $price_desc = ($price*$discount['rate']/100).'+'.$integral.'积分';
                    $price = $price*$discount['rate']/100;
                }else if(!empty($discount)){
                    $discount_id = $discount['discount_id'];
                    $price_desc = $price*$discount['rate']/100;
                    $price = $price*$discount['rate']/100;
                }else if($integral > 0){
                    $price_desc = $price.'+'.$integral.'积分';
                }
                $spec = SpecGoodsPrice::getOne(['item_id'=>$v['spec_price_goods_id'],'goods_id'=>$v['goods_id'],'key'=>$v['spec_key']],'item_id,key,key_name,price');

                $key = '';
                $key_name = '';

                if(!empty($spec)){
                    $key = $spec['key'];
                    $key_name = $spec['key_name'];
                    $price = $spec['price']*$v['goods_num'];
                    $real_price = $spec['price']*$v['goods_num'];
                    if(!empty($discount) && $integral > 0){
                        $price_desc = ($price*$discount['rate']/100).'+'.$integral.'积分';
                        $price = $price*$discount['rate']/100;
                    }else if(!empty($discount)){
                        $price_desc = $price*$discount['rate']/100;
                        $price = $price*$discount['rate']/100;
                    }else if($integral > 0){
                        $price_desc = $price.'+'.$integral.'积分';
                    }
                }

                $goodsList[] = [
                    'goods_id'=>$v['goods_id'],
                    'shop_id'=>$v['shop_id'],
                    'spec_price_goods_id'=>$v['spec_price_goods_id'],
                    'goods_name'=>$v['getGoods']['goods_name'],
                    'goods_sn'=>$v['getGoods']['goods_sn'],
                    'key'=>$key,
                    'key_name'=>$key_name,
                    'discount_id'=>$discount_id,
                    'shop_price'=>$real_price,
                    'market_price'=>$v['getGoods']['market_price'],
                    'cost_price' =>$v['getGoods']['cost_price'],
                    'real_price'=>$price,
                    'price_desc'=>$price_desc,
                    'original_img'=>$v['getGoods']['original_img'],
                    'cart_id'=>$v['id'],
                    'give_integral'=>$v['getGoods']['give_integral'],
                    'integral'=>$integral,
                    'goods_num'=>$v['goods_num']
                ];
                $shop_id = $v['shop_id'];

                if($v['getGoods']['is_free_shipping'] ==0){
                    $weight += $v['getGoods']['weight'];
                }

                $total_integral += $integral;
                $total_price += $price;
            }
        }else {
            if ($goods_id && $goods_num < 1) {
                JsonService::error('购买数量至少为1个');
            }
            $goods = GoodsModel::getOne(['goods_id' => $goods_id], 'goods_id,shop_id,goods_name,goods_sn,shop_price,market_price,cost_price,original_img,goods_type,sales_sum,comment_count,store_count,exchange_integral,give_integral,is_free_shipping,weight')->toArray();

            $price = $goods['shop_price'] * $goods_num;
            $real_price = $goods['shop_price'] * $goods_num;
            $price_desc = '';
            $integral = $goods['exchange_integral'];

            $goods['key'] = '';
            $goods['key_name'] = '';
            $goods['discount_id'] = 0;
            //是否折扣商品
            $time = time();
            $where2 = [['goods_id','=',$goods_id],['start_time','<',$time],['end_time','>',$time]];
            $discount = DiscountModel::getOne($where2);
            if(!empty($discount) && $integral > 0){
                $goods['discount_id'] = $discount['discount_id'];
                $price_desc = ($price*$discount['rate']/100).'+'.$integral.'积分';
                $price = $price*$discount['rate']/100;
            }else if(!empty($discount)){
                $goods['discount_id'] = $discount['discount_id'];
                $price_desc = $price*$discount['rate']/100;
                $price = $price*$discount['rate']/100;
            }else if($integral > 0){
                $price_desc = $price.'+'.$integral.'积分';
            }
            if($spec_item_id > 0){
                $spec = SpecGoodsPrice::getOne(['item_id'=>$spec_item_id,'goods_id'=>$goods['goods_id']],'item_id,key,key_name,price');
                if(!empty($spec)){
                    $goods['key'] = $spec['key'];
                    $goods['key_name'] = $spec['key_name'];
                    $price = $spec['price'] * $goods_num;
                    $real_price = $spec['price'] * $goods_num;

                    if(!empty($discount) && $integral > 0){
                        $price_desc = ($price*$discount['rate']/100).'+'.$integral.'积分';
                        $price = $price*$discount['rate']/100;
                    }else if(!empty($discount)){
                        $price_desc = $price*$discount['rate']/100;
                        $price = $price*$discount['rate']/100;
                    }else if($integral > 0){
                        $price_desc = $price.'+'.$integral.'积分';
                    }
                }
            }

            $goods['cart_id'] = 0;
            $goods['shop_price'] = $real_price;
            $goods['real_price'] = $price;
            $goods['price_desc'] = $price_desc;
            $goods['integral'] = $integral;
            $goods['goods_num'] = $goods_num;
            $goods['spec_price_goods_id'] = $spec_item_id;

            $goodsList = [$goods];

            $shop_id = $goods['shop_id'];
            $total_price = $price;
            $total_integral = $integral;
            if($goods['is_free_shipping'] ==0){
                $weight += $goods['weight'];
            }
        }
        //print_r($goodsList);die();
        $total['total_price'] = $total_price;
        $total['total_integral'] = $total_integral;

        //计算物流
        $shipping_price = GoodsModel::getFreight($this->member_id,$address_id,$shipping_code,$weight);
        //计算优惠劵
        $coupon_price = Coupon::getCouponMoney($this->member_id,$coupon_id);

        $car_price = array(
            'postFee'      => $shipping_price, // 物流费
            'couponFee'    => $coupon_price, // 优惠券
            'payables'     => number_format($total_price+$shipping_price-$coupon_price, 2, '.', ''), // 应付金额
            'goodsFee'     => $total_price,// 商品价格
            'total_integral'=>$total_integral,
            'shop_id'     =>$shop_id,
        );

        // 提交订单
        if ($_REQUEST['act'] == 'submit_order') {
            $member = Member::getOne(['id'=>$this->member_id]);
            if($member['integral'] < $total_integral){
                return JsonService::error('积分不足！');
            }
            $pay_name = '';
            $result = Order::addOrder($this->member_id,$address_id,$shipping_code,$invoice_title,$coupon_id,$car_price,$user_note,$pay_name,$goodsList); // 添加订单
            return json($result);
        }

        return JsonService::success($car_price,'计算成功');

    }

    /**
     * ajax 获取订单商品价格 或者提交 订单
     */
    public function cart4(){

        $order_id = input('order_id/d');
        $order_where = ['member_id'=>$this->member_id,'order_id'=>$order_id];
        $order = Order::getOne($order_where);
        if($order['order_status'] == 3){
            $this->error('该订单已取消',U("Home/Order/order_detail",array('id'=>$order_id)));
        }

        if(empty($order) || empty($this->member_id)){
            $order_order_list = url("index/login/login");
            header("Location: $order_order_list");
            exit;
        }
        // 如果已经支付过的订单直接到订单详情页面. 不再进入支付页面
        if($order['pay_status'] == 1){
            $order_detail_url = url("index/Order/order_detail",array('id'=>$order_id));
            header("Location: $order_detail_url");
            exit;
        }


        $this->assign('order',$order);
        return $this->fetch();
    }

}